package com.th.supcom.pds.recipefee.client.widget;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.pds.auditprescription.client.model.PdsPrescDetailCombineModel;
import com.th.supcom.pds.common.client.commom.PdsAuditPrescServiceFactory;
import com.th.supcom.pds.common.client.model.CodeConstants;
import com.th.supcom.pds.common.client.model.OfficeModel;
import com.th.supcom.pds.common.client.widget.PrescDetailGrid;
import com.th.supcom.pds.common.client.widget.PrescDetailGrid.ColumnConfigEnhance;
import com.th.supcom.pds.common.constant.KeysConstants;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.internal.client.model.PatientInfoModel;
import com.th.supcom.pds.internal.client.widget.MedicareCardField;
import com.th.supcom.pds.recipefee.client.business.RecipeFeeBusiness;
import com.th.supcom.pds.recipefee.client.common.RecipeFeeModuleEvents;
import com.th.supcom.pds.sortingdrug.client.model.PdsPrescDetailInfoModel;

/**
 * 收方收费主面板.
 * 
 * @author 杨冲
 */
public class RecipeFeeMainPanel extends ContentPanel
{
    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";
    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";
    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";
    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
    private RecipeFeeButtons m_buttons;
    private RecipeFeeFields m_fields;
    private static final String STOCK_SHORT = "0";
    private MedicareCardField m_medicareCardField;
    private PatientInfoModel m_patientInfoModel;
    private PrescDetailGrid <PdsPrescDetailInfoModel> m_prescDetailGrid;
    private RecipePanel m_recipePanel;
    public RecipeFeeMainPanel ()
    {
        init ();
        addListeners ();
    }

    /**
     * 改造prescDetailGrid用于收方收费
     * 
     * @return add by Zli
     */
    private ColumnConfigEnhance addAndDelCol ()
    {
        return new ColumnConfigEnhance ()
        {

            @Override
            public void enhance (final List <ColumnConfig> configs)
            {
                configs.remove (9);
                configs.remove (6);
                configs.remove (5);

                ColumnConfig column = null;
                column = new ColumnConfig ("color", "", 20);
                
                column.setRenderer (new GridCellRenderer <ModelData> ()
                {

                    @Override
                    public Object render (ModelData model, String property, ColumnData config, int rowIndex,
                                          int colIndex, ListStore <ModelData> store, Grid <ModelData> grid)
                    {
                        if ("1".equals (model.get ("checkFlag")))
                        {
                            return "<div style='background-color:orange;height:16px' title='需要审核'></div>";
                        }
                        if (model.get ("rcptNo")!=null)
                        {
                            return "<div style='background-color:red;height:16px' title='已收费'></div>";
                        }
                        // 需要做皮试，并且皮试结果为未作皮试或不通过（需要调用外部系统【儿科，非儿科】），绿色表示
                        /*
                         * if((Integer)model.get ("skinTest")==1&&"0".equals
                         * (model.get("qualifiedIndicator")+"")){ return
                         * "x-grid-row-bgcolor-green"; }
                         */
                        // 库存不足，用蓝绿色标示，进行人工调整执行科室
                        if (model.get ("stockFlag") != null)
                        {
                            return "<div style='background-color:green;height:16px' title='库存不足'></div>";
                        }

                        return "";
                    }
                });
                configs.add (1, column);

                column = new ColumnConfig ("packagePrice", "单价", 80);
                column.setRenderer (ClientUtils.getRenderer ("packagePrice"));
                configs.add (6, column);
                column = new ColumnConfig ("POT", "疗程", 120);
                configs.add (column);
                column = new ColumnConfig ("usageCodName", "用药途径", 120);
                configs.add (column);
                column = new ColumnConfig ("performedByName", "供药药房", 100);
                column.setEditor (getEditor (new OrgCombox ()));
                column.setRenderer (RecipeFeeUtils.performbyRender ());
                configs.add (column);

                column = new ColumnConfig ("sendDrugMode", "发药方式", 120);
                configs.add (column);
                column = new ColumnConfig ("takeWayCycle", "带走疗程", 120);
                RecipeFeeUtils.formatPosIntEditor (column);
                configs.add (column);
            }

        };
    }

    /**
     * 添加监听事件
     * 
     * add by Zli
     */
    private void addListeners ()
    {
        RecipeFeeUtils.buttonListener (m_buttons.getQueryBtn (), RecipeFeeModuleEvents.RECIPEFEE_QUERY);
        RecipeFeeUtils.buttonListener (m_buttons.getConfirmBtn (), RecipeFeeModuleEvents.RECIPEFEE_CONFIRM);
        RecipeFeeUtils.buttonListener (m_buttons.getClearBtn (), RecipeFeeModuleEvents.RECIPEFEE_CLEAR);
        RecipeFeeUtils.buttonListener (m_buttons.getPlasticBagBtn (), RecipeFeeModuleEvents.RECIPEFEE_ADDPLASTICBAG);
        final Map <Integer, EventType> map = new HashMap <Integer, EventType> ();
        map.put (KeysConstants.VK_O, RecipeFeeModuleEvents.RECIPEFEE_CONFIRM);
        map.put (KeysConstants.VK_Q, RecipeFeeModuleEvents.RECIPEFEE_QUERY);
        map.put (KeysConstants.VK_R, RecipeFeeModuleEvents.RECIPEFEE_CLEAR);
        map.put (KeysConstants.VK_P, RecipeFeeModuleEvents.RECIPEFEE_ADDPLASTICBAG);
        ClientUtils.addBlobalShortKey (this, map);
        RecipeFeeUtils.enterKeyDownListener (m_fields.getRecipeNoField (), RecipeFeeModuleEvents.RECIPEFEE_QUERY);
        // 控制可不可编辑
        RecipeFeeUtils.disableCellEdit (m_prescDetailGrid.getGrid ());
    }

    /**
     * 得到清屏按钮
     * 
     * @return add by Zli
     */
    public Button getClearBtn ()
    {

        return m_buttons.getClearBtn ();
    }

    public Button getConfirmBtn ()
    {

        return m_buttons.getConfirmBtn ();
    }

    private CellEditor getEditor (final OrgCombox combo)
    {
        combo.setEditable (false);
        // 执行科室发生变化时表格一列的数据进行相应的更新
        final CellEditor editor = new CellEditor (combo)
        {
            @Override
            public Object postProcessValue (final Object value)
            {
                if (value == null)
                {
                    return value;
                }
                m_prescDetailGrid.getGrid ().getStore ().getAt (super.row)
                                 .setPerformedBy(combo.getValue ().getCode ());

                return combo.getValue ().getName ();
            }

            @Override
            public Object preProcessValue (final Object value)
            {
                if (value == null)
                {
                    return value;
                }
                OfficeModel dictModel = null;
                for (final OfficeModel dict : combo.getStore ().getModels ())
                {
                    if (dict.getName ().equals (value.toString ()))
                    {
                        dictModel = dict;
                        break;
                    }
                }
                return dictModel;

            }

            @Override
            public void startEdit (final Element el, final Object value)
            {

                final PdsPrescDetailCombineModel pdsPrescDetailCombine = new PdsPrescDetailCombineModel ();
                pdsPrescDetailCombine.setQuantity (m_prescDetailGrid.getGrid ().getSelectionModel ().getSelectedItem ()
                                                                    .getQtySum());
                pdsPrescDetailCombine.setPhamCode (m_prescDetailGrid.getGrid ().getSelectionModel ().getSelectedItem ()
                                                                    .getPhamStdCode ());
                combo.loadData (pdsPrescDetailCombine);
                super.startEdit (el, value);
            }
        };
        listenCombox (combo);
        return editor;
    }

    public RecipeFeeFields getM_fields ()
    {
        return m_fields;
    }

    public MedicareCardField getMedicareCardField ()
    {
        return m_medicareCardField;
    }

    public PrescDetailGrid <PdsPrescDetailInfoModel> getM_prescDetailGrid ()
    {
        return m_prescDetailGrid;
    }

    public String getPatentId ()
    {
        return m_fields.getPatientIdField ().getValue ();
    }

    /**
     * 得到塑料袋按钮
     * 
     * @return add by Zli
     */
    public Button getPlasticBagBtn ()
    {

        return m_buttons.getPlasticBagBtn ();
    }

    public String getPname ()
    {
        return m_fields.getNameField ().getValue ();
    }

    public RecipePanel getRecipePanel ()
    {

        return m_recipePanel;
    }

    public String getRefundMoney ()
    {
        return m_fields.getBalanceField ().getValue ();
    };

    private void init ()
    {
        this.setHeaderVisible (false);
        this.setLayout (new BorderLayout ());

        RecipeFeePatientInfoPanel m_recipeFeePatientInfoPanel;
        m_buttons = new RecipeFeeButtons ();
        m_fields = new RecipeFeeFields ();
        m_prescDetailGrid = new PrescDetailGrid <PdsPrescDetailInfoModel> (addAndDelCol ());
        m_prescDetailGrid.setButtonAlign (HorizontalAlignment.CENTER);
        m_prescDetailGrid.addButton (m_buttons.getPlasticBagBtn ());
        m_prescDetailGrid.addButton (m_buttons.getConfirmBtn ());
        m_prescDetailGrid.addButton (m_buttons.getClearBtn ());
        m_recipeFeePatientInfoPanel = new RecipeFeePatientInfoPanel (m_fields, m_buttons);
        m_recipePanel = new RecipePanel ();
        addMedicareCard ();
        m_medicareCardField.setFieldLabel ("卡信息");
        m_recipeFeePatientInfoPanel.addMedicareCard (m_medicareCardField);
        m_recipeFeePatientInfoPanel.initUI ();

        final BorderLayoutData centerData = new BorderLayoutData (LayoutRegion.CENTER);
        centerData.setMargins (new Margins (0, 0, 0, 0));
        final BorderLayoutData westData = new BorderLayoutData (LayoutRegion.WEST, 300);
        westData.setMargins (new Margins (0, 0, 0, 2));
        final BorderLayoutData northData = new BorderLayoutData (LayoutRegion.NORTH, 180);
        northData.setMargins (new Margins (2, 0, 0, 0));

        add (m_recipeFeePatientInfoPanel, northData);
        add (m_prescDetailGrid, centerData);
        add (m_recipePanel, westData);
        ToolBar toolBar = RecipeFeeUtils.createColorShow ();
        this.setBottomComponent (toolBar);
    }

    private void listenCombox (final OrgCombox combo)
    {
        combo.addSelectionChangedListener (new SelectionChangedListener <OfficeModel> ()
        {
            @Override
            public void selectionChanged (final SelectionChangedEvent <OfficeModel> se)
            {
                // 得到执行科室，根据编码和执行科室判断库存
                if (se.getSelectedItem () == null)
                {
                    return;
                }
                PdsAuditPrescServiceFactory.getRecipeFeeService ().verifyStock (se.getSelectedItem ().getCode (),
                                                                                m_prescDetailGrid.getGrid ()
                                                                                                 .getSelectionModel ()
                                                                                                 .getSelectedItem ()
                                                                                                 .getPhamStdCode (),
                                                                                new AsyncCallback <Integer> ()
                                                                                {

                                                                                    @Override
                                                                                    public void onFailure (final Throwable caught)
                                                                                    {
                                                                                        ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                                                     null);
                                                                                    }

                                                                                    @Override
                                                                                    public void onSuccess (final Integer result)
                                                                                    {
                                                                                        if (m_prescDetailGrid.getGrid ()
                                                                                                             .getSelectionModel ()
                                                                                                             .getSelectedItem ()
                                                                                                             .getQtySum() <= result)
                                                                                        {
                                                                                            m_prescDetailGrid.getGrid ()
                                                                                                             .getSelectionModel ()
                                                                                                             .getSelectedItem ()
                                                                                                             .setStockFlag (null);
                                                                                            return;
                                                                                        }
                                                                                        m_prescDetailGrid.getGrid ()
                                                                                                         .getSelectionModel ()
                                                                                                         .getSelectedItem ()
                                                                                                         .setStockFlag (STOCK_SHORT);
                                                                                    }
                                                                                });
            }
        });
    }
    /**
     * 添加刷卡组件
     */
    private void addMedicareCard ()
    {
        m_medicareCardField = new MedicareCardField (this)
        {
            @Override
            public void handleEventAfter ()
            {
                RecipeFeeUtils.clearInfo (RecipeFeeMainPanel.this);
                m_patientInfoModel = RecipeFeeUtils.initPatientInfo (m_medicareCardField);
                RecipeFeeMainPanel.this.mask ("正在拼命加载中");
                if (null == m_patientInfoModel)
                {
                    RecipeFeeMainPanel.this.unmask ();
                    MessageBox.alert (CodeConstants.PROMPT, "此患者不存在，请办理就诊卡！", null);
                    return;
                }
                RecipeFeeUtils.initPatientData (m_patientInfoModel,m_fields);
                String patientId=m_patientInfoModel.getPatiId ();
                Map <String, Object>map=new HashMap <String, Object> ();
                map.put ("patientId", patientId);
                map.put ("flag", 2);
                RecipeFeeBusiness.queryByCardNo (map, RecipeFeeMainPanel.this);
                return;
            }
        };
    }
    public PrescDetailGrid <PdsPrescDetailInfoModel> getPrescDetailGrid ()
    {
        return m_prescDetailGrid;
    }

    public PatientInfoModel getPatientInfoModel ()
    {
        return m_patientInfoModel;
    }
    public void setPatientInfoModel (PatientInfoModel allInfoModel)
    {
        m_patientInfoModel = allInfoModel;
    }
    public void poupWindow ()
    {
        //弹出塑料袋面板
        BagWindow bagWindow=new BagWindow();
        bagWindow.show ();
        
        bagWindow.addListener (BagWindow.cancelBack, new Listener <AppEvent>()
        {

            @Override
            public void handleEvent (AppEvent be)
            {
                PdsPrescDetailInfoModel pdsPrescDetailInfoModel=null;
                //进行判断 如果表格里有塑料袋 更新塑料袋的个数和价格
                pdsPrescDetailInfoModel=m_prescDetailGrid.getGrid ().getStore ().findModel ("phamName", "塑料袋");
                if(pdsPrescDetailInfoModel==null){
                    pdsPrescDetailInfoModel=new PdsPrescDetailInfoModel();
                    pdsPrescDetailInfoModel.setPhamName ("塑料袋");
                    Double number=(Double)be.getData ("number");
                    pdsPrescDetailInfoModel.setUnitQty(number);
                    pdsPrescDetailInfoModel.setPackagePrice(0.2);
                    pdsPrescDetailInfoModel.setCosts (0.2*number);
                    m_prescDetailGrid.getGrid ().getStore ().add (pdsPrescDetailInfoModel); 
                }else{
                    //进行更新
                    Double number=(Double)be.getData ("number");
                    pdsPrescDetailInfoModel.setUnitQty(number);
                    pdsPrescDetailInfoModel.setPackagePrice (0.2);
                    pdsPrescDetailInfoModel.setCosts (0.2*number);
                    m_prescDetailGrid.getGrid ().getStore ().update (pdsPrescDetailInfoModel);
                }
               
            }
        });
       
    }
    public RecipeFeeFields getFields ()
    {
        return m_fields;
    }
}
